package baseAPI;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.control.ListView;

public class MyServer implements Runnable {

    //Server端监听的端口号
    public static final int PORT = 9999;
    //映射表 存放每个socket地址(IP:Port)及其对应的PrintWriter
    //为群发消息做准备
    Map<Integer,Socket> map = new HashMap<>();

    Set<Socket> sockets = new HashSet<>();
    Set<Socket> selectedSockets = new HashSet<>();

    public MyServer() {

    }


    /**
     * 更新UI界面的IP和Port
     */
    public void updateIpAndPort() {
        //用于在非UI线程更新UI界面
        Platform.runLater(() -> {

        });
    }

    @Override
    public void run() {
        //updateIpAndPort();
        ServerSocket server;
        Socket socket;
        try {
            server = new ServerSocket(PORT);

            while (true) {
                if(!server.isClosed()){System.out.println("服务器开启");}

                socket = server.accept();
                sockets.add(socket);
                if(!socket.isClosed()){System.out.println("端口开启");}

                String remoteSocketAddress = socket.getRemoteSocketAddress().toString().substring(1);
                System.out.println("客户端ip地址为"+remoteSocketAddress);

                OutputStream out = socket.getOutputStream();
                PrintWriter pWriter = new PrintWriter(out);
                selectedSockets.add(socket);
                sendMessage("欢迎光临本酒店");
                //一个客户端接入就启动一个handler线程去处理,同时存入ip地址和socket
                new Thread(new ReceiveHandler(map, socket)).start();
            }
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

    //单发消息
    public void chooseClient(int roomNumber){
            selectedSockets.add(map.get(roomNumber));
    }

    //群发消息
    public void chooseClient(ObservableList<Integer> roomNumber){
        for(int roomnumber : roomNumber)  selectedSockets.add(map.get(roomnumber));
    }

    public void  sendMessage(String message){
        OutputStream out = null;
        try {
            for(Socket socket : selectedSockets) {
                out = socket.getOutputStream();
                byte[] bytes = message.getBytes();
                int messageLength = bytes.length;
//                PrintWriter pWriter = new PrintWriter(out);
                message = (messageLength) + message;
                for(int i = 0;i<4- String.valueOf(messageLength).length();i++){
                    message = "0" + message;
                }
                bytes = message.getBytes();
                //发消息
                out.write(bytes);
                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            selectedSockets.clear();
        }
    }
}